﻿using com.uplus.common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Bill.Biz;
using WebApi.Common;
using WebApi.Models;

namespace WebApi.Controllers
{
    public class UserController : BaseController
    {

        #region 获取数据列表
        /// <summary>
        /// GetPageToList
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<ResponseDataUser> GetPageToList([FromBody] dynamic param)
        {
            ResponseDataUser res = new ResponseDataUser();

            try
            {
                int recordCount = 0;
                int totalPage = 0;
                List<UserModel> data = BizBase.Get<BizUser>().GetPageList(param, ref recordCount, ref totalPage);
                if (data != null && data.Count > 0)
                {
                    res.code = 200;
                    res.msg = "success";
                    res.user = data;
                    res.totalPage = totalPage;
                    res.records = recordCount;
                }
                return new JsonResult(res);

            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "GetPageToList", ex);
            }

        }
        #endregion

        #region 根据编码获取单条数据
        /// <summary>
        /// 根据编码获取单条数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<UserModel> Get(string code)
        {
            ResponseDataUser res = new ResponseDataUser();
            UserModel data = BizBase.Get<BizUser>().Get(code);
            try
            {
                if (data != null)
                {
                    res.code = 200;
                    res.msg = "success";
                    res.user = data;
                }

                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "Get", ex);
            }
        }
        #endregion

        #region 编辑数据
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit([FromBody] UserModel model)
        {
            ResponseDataUser result = new ResponseDataUser();
            try
            {

                if (string.IsNullOrEmpty(model.userID))
                {
                    BizBase.Get<BizUser>().Add(model);
                }
                else
                {
                    BizBase.Get<BizUser>().Update(model);
                }
                result.code = 200;
                result.msg = "success";
                result.user = null;

                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(result, "Edit", ex);
            }

        }
        #endregion

        #region 删除数据
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="code">广告编码</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<ResponseDataUser> Delete(string code)
        {
            ResponseDataUser res = new ResponseDataUser();
            try
            {
                int result = BizBase.Get<BizUser>().Delete(code);
                if (result == 1)
                {
                    res.code = 200;
                    res.msg = "删除成功";
                    res.user = null;
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "Delete", ex);
            }
        }
        #endregion

        #region 用户登录 Login
        /// <summary>
        /// 用户登录 add by cfl  2022-04-14
        /// </summary>
        /// <param name="param"></param>

        [HttpPost]
        public ActionResult<ResponseData> Login([FromBody] dynamic param)
        {
            string userName = "";
            string userPwd = "";
            ResponseDataEx res = new ResponseDataEx();
            try
            {
                LoginPostData postData = JsonConvert.DeserializeObject<LoginPostData>(JsonConvert.SerializeObject(param));
                if (postData != null)
                {
                    userName = postData.username;
                    userPwd = postData.password;
                }
                UserModel model = BizBase.Get<BizUser>().GetModelByNameAndPassWord(userName, userPwd);
                if (model != null)
                {

                    res.code = 200;
                    res.msg = "操作成功";
                    res.token = BizBase.Get<BizUser>().GetToken(model);
                }
                else
                {
                    res.code = 201;
                    res.msg = "用户名或者密码错误";
                    res.token = null;
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "Login", ex);
            }
        }
        #endregion

        #region 用户注册 Register
        /// <summary>
        /// 用户注册 add by cfl  2022-04-14
        /// </summary>
        /// <param name="param"></param>
        [HttpPost]
        public ActionResult<ResponseData> Register([FromBody] dynamic param)
        {
            ResponseDataMsg res = new ResponseDataMsg();
            try
            {
                RegisterPostData postData = JsonConvert.DeserializeObject<RegisterPostData>(JsonConvert.SerializeObject(param));
                if (postData != null)
                {
                    UserModel model = new UserModel();
                    model.avatar = postData.avatar;
                    model.idCard = postData.idCard;
                    model.userName = postData.userName;
                    switch (postData.sex)
                    {
                        case "男":
                            model.sex = "0";
                            break;
                        case "女":
                            model.sex = "1";
                            break;
                        default:
                            break;
                    }
                    model.userPwd = postData.password;
                    model.nickName = postData.nickName;
                    model.phonenumber = postData.phonenumber;
                    model.email = postData.email;
                    BizBase.Get<BizUser>().Add(model);
                }
                res.code = 200;
                res.msg = "注册成功";
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "Register", ex);
            }
        }
        #endregion

        #region 查询用户信息 GetInfo
        /// <summary>
        /// 根据编码获取单条数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<UserModel> GetInfo()
        {
            ResponseDataUser res = new ResponseDataUser();

            try
            {
                var accessToken = Request.Headers["Authorization"];
                DateTime utcNow = DateTime.UtcNow;
                string key = AppConfigurtaion.GetSecondSection("JwtSetting", "SecurityKey"); //"d0ecd23c-dfdb-4005-a2ea-0fea210c858a";
                string jwtIssuerUplus = AppConfigurtaion.GetSecondSection("JwtSetting", "Issuer"); 
                string jwtAudienceUplus = AppConfigurtaion.GetSecondSection("JwtSetting", "Audience"); 
                SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));
                //校验token
                var validateParameter = new TokenValidationParameters()
                {
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtIssuerUplus,
                    ValidAudience = jwtAudienceUplus,
                    IssuerSigningKey = securityKey,
                };

                //校验并解析token
                var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(accessToken, validateParameter, out SecurityToken validatedToken);//validatedToken:解密后的对象
                var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //获取payload中的数据 
                dynamic dataJson =  JsonConvert.DeserializeObject<dynamic>(jwtPayload);
                string UserId = dataJson["UserID"];
                UserModel data = BizBase.Get<BizUser>().Get(UserId);
          
                if (data != null)
                {
                    res.code = 200;
                    res.msg = "操作成功";
                    res.user = data;
                }
                else
                {
                    res.code = 203;
                    res.msg = "暂无数据";
                    res.user = null;
                }

                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "GetInfo", ex);
            }
        }


        #endregion

        #region 修改个人基本信息 EditUser
        /// <summary>
        /// 修改个人基本信息  add by cfl  2022-04-14
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPut]
        public ActionResult<UserModel> EditUser([FromBody] dynamic param)
        {
            ResponseDataMsg res = new ResponseDataMsg();

            try
            {
                RegisterPostData postData = JsonConvert.DeserializeObject<RegisterPostData>(JsonConvert.SerializeObject(param));
                var accessToken = Request.Headers["Authorization"];
                DateTime utcNow = DateTime.UtcNow;
                string key = AppConfigurtaion.GetSecondSection("JwtSetting", "SecurityKey"); //"d0ecd23c-dfdb-4005-a2ea-0fea210c858a";
                string jwtIssuerUplus = AppConfigurtaion.GetSecondSection("JwtSetting", "Issuer");
                string jwtAudienceUplus = AppConfigurtaion.GetSecondSection("JwtSetting", "Audience");
                SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));
                //校验token
                var validateParameter = new TokenValidationParameters()
                {
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtIssuerUplus,
                    ValidAudience = jwtAudienceUplus,
                    IssuerSigningKey = securityKey,
                };

                //校验并解析token
                var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(accessToken, validateParameter, out SecurityToken validatedToken);//validatedToken:解密后的对象
                var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //获取payload中的数据 
                dynamic dataJson = JsonConvert.DeserializeObject<dynamic>(jwtPayload);
                string UserId = dataJson["UserID"];
                UserModel data = BizBase.Get<BizUser>().Get(UserId);
                if (data != null)
                {
                    data.email = postData?.email;
                    data.idCard = postData?.idCard;
                    data.nickName = postData?.nickName;
                    data.phonenumber = postData?.phonenumber;
                    data.sex = postData.sex == "男" ? "0" : "1";
                    BizBase.Get<BizUser>().Update(data);
                    res.code = 200;
                    res.msg = "修改成功";
                }
                else
                {
                    res.code = 203;
                    res.msg = "暂无数据";
                }

                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "EditUser", ex);
            }
        }
        #endregion

        #region 修改用户密码 ResetPwd
        /// <summary>
        /// 修改用户密码  add by cfl  2022-04-14
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPut]
        public ActionResult<UserModel> ResetPwd([FromBody] dynamic param)
        {
            ResponseDataMsg res = new ResponseDataMsg();

            try
            {
                ResetPwdPutData putData = JsonConvert.DeserializeObject<ResetPwdPutData>(JsonConvert.SerializeObject(param));
                var accessToken = Request.Headers["Authorization"];
                DateTime utcNow = DateTime.UtcNow;
                string key = AppConfigurtaion.GetSecondSection("JwtSetting", "SecurityKey"); //"d0ecd23c-dfdb-4005-a2ea-0fea210c858a";
                string jwtIssuerUplus = AppConfigurtaion.GetSecondSection("JwtSetting", "Issuer");
                string jwtAudienceUplus = AppConfigurtaion.GetSecondSection("JwtSetting", "Audience");
                SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));
                //校验token
                var validateParameter = new TokenValidationParameters()
                {
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtIssuerUplus,
                    ValidAudience = jwtAudienceUplus,
                    IssuerSigningKey = securityKey,
                };

                //校验并解析token
                var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(accessToken, validateParameter, out SecurityToken validatedToken);//validatedToken:解密后的对象
                var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //获取payload中的数据 
                dynamic dataJson = JsonConvert.DeserializeObject<dynamic>(jwtPayload);
                string UserId = dataJson["UserID"];
                UserModel data = BizBase.Get<BizUser>().Get(UserId);
                if (data != null)
                {
                    if (data.userPwd == putData?.oldPassword&&!string.IsNullOrEmpty(data.userPwd))
                    {
                        data.userPwd = putData?.newPassword;
                        BizBase.Get<BizUser>().Update(data);
                        res.code = 200;
                        res.msg = "修改成功";
                    }
                    else
                    {
                        res.code = 201;
                        res.msg = "原密码错误";
                    }
                }
                else
                {
                    res.code = 203;
                    res.msg = "暂无数据";
                }

                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "ResetPwd", ex);
            }
        }
        #endregion

        #region 获取验证码
        [HttpGet]
        public ActionResult<ResponseDataFile> GetCode()
        {
            ResponseDataFile res = new ResponseDataFile();
            ModelData dt = new ModelData();
            try
            {
                VerificationCodeHelper vcode = new VerificationCodeHelper();
                string codeStr = vcode.GetRandomCode();
                if (!string.IsNullOrEmpty(codeStr))
                {
                    Hei.Captcha.SecurityCodeHelper securityCode = new Hei.Captcha.SecurityCodeHelper();
                    byte[] arrImg = securityCode.GetEnDigitalCodeByte(codeStr);
                    //byte[] arrImg = vcode.GetVCode(codeStr);
                    //Session["code"] = codeStr;
                    //HttpContext.Session.SetString("code", codeStr);
                   // CodeModel codeModel = new CodeModel();
                    //codeModel.Code = BizBase.Get<BizAutoCode>().NextCode("TbCode", "pkCode", 4);
                   // codeModel.SCode = codeStr;
                   // BizBase.Get<BizCode>().Add(codeModel);
                   // dt.Info = codeModel.Code;
                    res.file = File(arrImg, "image/png");
                }
                res.code = 200;
                res.msg = "操作成功";
                
            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "GetCode", ex);
            }
            return res;
        }
        private bool ValidateCaptchaCode(string userInputCaptcha)
        {
            var isValid = userInputCaptcha.Equals(HttpContext.Session.GetString("code"), StringComparison.OrdinalIgnoreCase);
            HttpContext.Session.Remove("code");
            return isValid;
        }
        #endregion

        #region 获取验证码
        [HttpGet]
        public ActionResult<ResponseDataFile> GetCode2()
        {
            ResponseDataFile res = new ResponseDataFile();
            ModelData dt = new ModelData();
            try
            {
                string code = "";
                MemoryStream ms = VierificationCodeServices.Create(out code);
                HttpContext.Session.SetString("LoginValidateCode", code);
                Response.Body.Dispose();
                res.file = File(ms.ToArray(), @"image/png");
                res.code = 200;
                res.msg = "操作成功";

            }
            catch (Exception ex)
            {
                return this.ControllerExHandler(res, "GetCode", ex);
            }
            return res;
        }
        #endregion


    }
}
